<template>
  <div class="exchange">
    <div class="main">
      <div class="cont flex">
        <div class="flex" style="">
          <!-- 支付币种 -->
          <div class="flexLeft">{{$t('swap.s3')}}</div>
          <div class="flexRight">
            <el-input :placeholder="$t('swap.s4')" v-model="coinSelect.pay.number"
            type="number"
            clearable
            @input="handlePayNumberInput"
            @blur="handleNumberBlur('pay', coinSelect.pay.number, coinSelect.pay.decimal)"
            class="input-with-select">
              <el-select v-model="coinSelect.pay.coin"
              @change="coinSelect.timer = new Date().getTime()"
              slot="prepend" :placeholder="$t('swap.s61')"
              class="selectClass">
                <div class="slotClass flex" slot="prefix">
                  <img class="checkAreaImg" :src="coinSelect.pay.logo" alt=""/>
                </div>
                <template v-for="(item, index) in coinList">
                  <el-option
                  :label="item.coin"
                  :value="item.coin"
                  :key="index">
                    <div class="slotClass flex">
                      <img class="checkAreaImg" :src="item.logo" v-if="item.logo" alt=""/>
                      <span>{{ item.coin }}</span>
                    </div>
                  </el-option>
                </template>
              </el-select>
            </el-input>
            <!-- 最小兑换额度不小于0.1EOS -->
            <div class="errorCodexPay" style="padding:3px 0 0 130px; font-size:12px; color:#f00"
            v-if="errorCodexPay">
              {{$t('swap.s62')}}
            </div>
            <div class="mt" style="margin-top: 20px !important;">
              <div class="flexb balance"
                v-if="scatter && scatter.identity
                && scatter.chain === 'eos'">
                <div></div>
                <div>
                  <!-- 可用余额 -->
                  <span style="cursor: pointer;" @click="coinSelect.pay.number = balance;handlePayNumberInput()">
                    {{$t('swap.s16')}}：
                    <span v-if="balance !== null">{{balance}}</span>
                    <i v-else class="el-icon-refresh el-icon-loading"></i>
                    {{coinSelect.pay.coin}}
                  </span>
                  <!-- 手续费 -->
                  <span style="margin-left: 30px;">{{$t('swap.s26')}}：{{shouxufei * 100}}%</span>
                </div>
              </div>
              <div v-else class="flexb balance">&nbsp;</div>
            </div>
          </div>
        </div>
        <!-- 得到币种 -->
        <div class="flex" style="padding-top: 35px;">
          <div class="flexLeft">{{$t('swap.s5')}}</div>
          <div class="flexRight" style="margin-top: 0;">
            <!-- 预计到账数量 -->
            <el-input :placeholder="$t('swap.s6')" v-model="coinSelect.get.number"
            type="number"
            clearable
            @input="handleGetNumberInput"
            @blur="handleNumberBlur('get', coinSelect.get.number, coinSelect.get.decimal)"
            class="input-with-select">
              <el-select v-model="coinSelect.get.coin"
              @change="coinSelect.timer = new Date().getTime()"
              slot="prepend" :placeholder="$t('swap.s61')"
              class="selectClass">
                <div class="slotClass flex" slot="prefix">
                  <img class="checkAreaImg" :src="coinSelect.get.logo" alt=""/>
                </div>
                <template v-for="(item, index) in coinList">
                  <el-option
                  v-if="item.coin !== coinSelect.pay.coin"
                  :label="item.coin"
                  :value="item.coin"
                  :key="index">
                    <div class="slotClass flex">
                      <img class="checkAreaImg" :src="item.logo" alt=""/>
                      <span>{{ item.coin }}</span>
                    </div>
                  </el-option>
                </template>
              </el-select>
            </el-input>
          </div>
        </div>
        <span class="centIcon" @click="handleChangeCoin">
          <i class="iconfont icon-huaban23-copy-copy"></i>
        </span>
      </div>
      <div class="nowPrice flex">
        <!-- <div v-if="coinSelect.get.coin !== 'EOS' && coinSelect.pay.coin !== 'EOS'">
          {{coinSelect.get.coin}}/{{coinSelect.pay.coin}}:
        </div>
        <div v-else>
          <span v-if="coinSelect.pay.coin === 'EOS'">
            {{coinSelect.pay.coin}}/{{coinSelect.get.coin}}:
          </span>
          <span v-if="coinSelect.get.coin === 'EOS'">
            {{coinSelect.get.coin}}/{{coinSelect.pay.coin}}:
          </span>
        </div> -->
        <!-- 当前价格： -->
        <!-- <div class="ml nowPriceItem">
          <span>{{$t('swap.s7')}}：</span>
          <span>{{coinInfo.price}}</span>
        </div> -->
        <!-- 兑换比例： -->
        <div class="ml nowPriceItem">
          <div>{{$t('swap.s17')}}：</div>
          <div v-if="coinSelect.pay.coin === 'EOS' && coinSelect.get.coin !== 'EOS'">
            1 {{ coinSelect.pay.coin }} = {{toFixed(coinInfo.bl, 8)}} {{ coinSelect.get.coin }} </div>
          <div v-if="coinSelect.pay.coin !== 'EOS' && coinSelect.get.coin === 'EOS'">
            1 {{ coinSelect.pay.coin }} = {{toFixed(coinInfo.price, 8)}} {{ coinSelect.get.coin }} </div>
          <div v-if="coinSelect.pay.coin !== 'EOS' && coinSelect.get.coin !== 'EOS'">
            1 {{ coinSelect.pay.coin }} = {{toFixed(coinInfo.price, 8)}} {{ coinSelect.get.coin }} </div>
        </div>
        <!-- 预估成交价格： -->
        <div class="ml nowPriceItem">
          <div>{{$t('swap.s8')}}(
            <span v-if="coinSelect.get.coin !== 'EOS' && coinSelect.pay.coin !== 'EOS'">
              {{coinSelect.get.coin}}/{{coinSelect.pay.coin}}
            </span>
            <span v-else-if="(coinSelect.pay.coin === 'EOS' && coinSelect.get.coin === 'USDT') ||
            (coinSelect.pay.coin === 'USDT' && coinSelect.get.coin === 'EOS') ||
            (coinSelect.pay.coin === 'EOS' && coinSelect.get.coin === 'USN') ||
            (coinSelect.pay.coin === 'USN' && coinSelect.get.coin === 'EOS')">
              <span v-if="coinSelect.pay.coin === 'EOS'">
                {{coinSelect.get.coin}}/{{coinSelect.pay.coin}}
              </span>
              <span v-if="coinSelect.get.coin === 'EOS'">
                {{coinSelect.pay.coin}}/{{coinSelect.get.coin}}
              </span>
            </span>
            <span v-else>
              <span v-if="coinSelect.pay.coin === 'EOS'">
                {{coinSelect.pay.coin}}/{{coinSelect.get.coin}}
              </span>
              <span v-if="coinSelect.get.coin === 'EOS'">
                {{coinSelect.get.coin}}/{{coinSelect.pay.coin}}
              </span>
            </span>
          )：
          </div>
          <div>
            <span class="mr" v-if="coinSelect.pay.coin === 'EOS' && coinSelect.get.coin !== 'EOS'">
              <span v-if="coinSelect.get.coin === 'USDT' || coinSelect.get.coin === 'USN'">
                {{Number(coinSelect.pay.number) ? toFixed(accDiv(1, accDiv(1, coinInfo.ygPrice)), 8) : toFixed(accDiv(1, coinInfo.price), 8)}}
              </span>
              <span v-else>
                {{Number(coinSelect.pay.number) ? toFixed(accDiv(1, coinInfo.ygPrice), 8) : coinInfo.price}}
              </span>
            </span>
            <span class="mr" v-else>
              <span v-if="(coinSelect.pay.coin === 'USDT' && coinSelect.get.coin === 'EOS') ||
              coinSelect.pay.coin === 'USN' && coinSelect.get.coin === 'EOS'">
                {{Number(coinSelect.pay.number) ? toFixed(accDiv(1, coinInfo.ygPrice), 8) : toFixed(accDiv(1, coinInfo.price), 8)}}
              </span>
              <span v-else>
                {{Number(coinSelect.pay.number) ? coinInfo.ygPrice : coinInfo.price}}
              </span>
            </span>
            <!-- 溢价率 滑点比例 -->
            <el-tooltip placement="bottom" effect="light" v-if="Number(coinSelect.pay.number)">
              <div slot="content" class="cozyTipContent">
                <p v-if="Number(coinInfo.yjlv) < 0">{{$t('swap.s81', {num: Math.abs(Number(coinInfo.yjlv))})}}</p>
                <p v-if="Number(coinInfo.yjlv) > 0">{{$t('swap.s9', {num: Math.abs(Number(coinInfo.yjlv))})}}</p>
              </div>
              <span class="cozyTip">
                <span v-if="Number(coinInfo.yjlv) * -1 > 0" style="color:#00be66">
                  +{{Number(coinInfo.yjlv) * -1}}%
                  <i class="iconfont icon-huaban"></i>
                </span>
                <span style="color: red;" v-else>
                  {{Number(coinInfo.yjlv) * -1}}%
                  <i class="iconfont icon-huaban"></i>
                </span>
              </span>
            </el-tooltip>
          </div>
        </div>
        <!-- 池内存币数据 -->
        <div class="ml nowPriceItem" v-if="coinSelect.pay.coin === 'EOS' || coinSelect.get.coin === 'EOS'">
          <div>{{$t('swap.s18')}}：</div>
          <!-- 池内存币数据 -->
          <div>
            <span>{{handleReturnPool().quote_quantity}}  &nbsp; {{handleReturnPool().base_quantity}} </span>
            <!-- 立即做市 -->
            <span class="colorThis" style="cursor: pointer; margin-left: 10px;"
              @click="handleToMarket">{{$t('swap.s94')}}＞
            </span>
          </div>
        </div>
        <!-- <div class="ml nowPriceItem" v-else>&nbsp;</div> -->
      </div>
      <div>
        <!-- 免费cpu -->
        <div v-if="scatter && scatter.identity
          && scatter.chain === 'eos'
          && scatter.by !== 'mobileWallet'"
          class="flexc"
          style="margin-top: 50px;">
          <div class="freeCpu flex" :style="$store.state.app.language === 'en' ? 'line-height: 15px;' : 'line-height: 10px;'">
            <el-checkbox v-model="freeCpuChecked"
            :style="$store.state.app.language === 'en' ? 'margin-top: -2px;' :''"
            :disabled="userInfo && !userInfo.remainFreeOrderCount">
              <free-cpu :user="userInfo" :embed="embed"/>
            </el-checkbox>
          </div>
        </div>
        <!-- 免费cpu end-->
        <div class="flexc">
          <el-button
          v-if="scatter && scatter.chain === 'eos' && scatter.identity"
          type="primary"
          class="btn"
          @click="handleSubmit"
          v-loading="loading">
            {{$t('swap.s1')}}
          </el-button>
          <el-button type="primary" class="btn" :class="{'grayBtn': 1}" @click="handleWalletPermission('EOS')" v-else>
            {{ $t('swap.s98') }}
          </el-button>
        </div>
        <div class="center tipCls" v-if="coinSelect.pay.coin !== 'EOS' && coinSelect.get.coin !== 'EOS'">
          <span>
          {{$t('swap.s45')}}</span>
        </div>
      </div>
    </div>
    <!-- 温馨提示 服务暂停-->
    <div v-if="stopSwap">
      <tips
        @close="handleTips"
        :text="stopSwapText"
        :width="400"
        :showBtn = true
        @listenTips="handleTips" />
    </div>
    <!-- 扫码交易 -->
    <el-dialog
      class="dialogPay"
      :close-on-click-modal="true"
      :visible.sync="tradingPay"
      width="550px"
      center>
      <pay-code :payData="payData" :tradingPay="tradingPay" />
    </el-dialog>
  </div>
</template>

<script>
import { bitModel } from '@/utils/eos/bitpeicurrex';
import PayCode from '@/components/PayCodeDialog';
import FreeCpu from '@/components/FreeCpu';
import Tips from '@/components/Tips'; // 弹出提示
// accAdd、accSub、accMul、accDiv
import { toFixed, accAdd, accSub, accMul, accDiv, toNonExponential, getTargetOrigin } from '@/utils/validate';
import Bus from '@/utils/bus';

export default {
  name: 'exchange', // 兑换
  data() {
    return {
      loading: false,
      coinList: [],
      coinSelect: { // 选择后数据
        pay: {
          coin: 'EOS',
          number: null, // 兑换数量
          logo: '', // 图标
        },
        get: {
          coin: 'NDX',
          number: null, // 得到数量
          logo: '', // 图标
        },
        pair_id: null,
        timer: null,
      },
      coinInfo: { // 交易对信息
        price: 0,
        ygPrice: 0,
        bili: 0,
        yjlv: 0 // 溢价率 =（当前价格-预估成交价）/当前价格
      },
      shouxufei: 0.003, // 手续服
      balance: null, // 余额
      errorCodexPay: false, // 错误提示
      freeCpuChecked: false, // 是否使用免费cpu
      userInfo: {}, // 用户信息
      stopSwap: false, // 服务暂停
      stopSwapType: -1, // 0-服务暂停 1-单个币种暂停
      stopSwapText: '',
      payCodeStr: '', // 支付币种名
      getCodeStr: '', // 得到币种名
      tradingPay: false, // 扫码交易
      payData: {},
    }
  },
  components: {
    FreeCpu,
    Tips,
    PayCode,
  },
  props: {
    symbolList: Array,
    scatter: Object,
    symbolScience: String,
    user: Object,
    embed: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    stopSwapType: function change() {
      if (this.stopSwapType === 0) {
        this.stopSwapText = this.$t('swap.s54');
        return;
      }
      this.stopSwapText = `${this.payCodeStr}${this.payCodeStr && this.getCodeStr ? ', ' : ''}${this.getCodeStr} ${this.$t('swap.s60')}`;
    },
    '$store.state.app.scatter.identity': {
      handler: function listen(val) {
        if (!val) return;
        this.handleBlanceIvit();
      },
      deep: true,
    },
    symbolList: function change(sList) {
      this.coinList = [];
      if (sList.length > 0) {
        const baseArr = sList.map(v => v.base);
        const quoteArr = sList.map(v => v.quote);
        baseArr.push(...quoteArr);
        this.coinList = baseArr.filter((item, index, self) => {
          const i = self.findIndex(v => v.filterion === item.filterion);
          return self.indexOf(item) === i;
        });
        // 触发更新
        this.coinSelect.timer = new Date().getTime();
      }
    },
    'coinSelect.timer': function change() {
      const val = this.coinSelect;
      let list = JSON.stringify(this.coinList);
      list = JSON.parse(list);
      const payItem = list.find(v => v.coin === val.pay.coin);
      if (payItem) {
        this.coinSelect.pay = payItem;
        this.coinSelect.pay.number = null;
        this.coinSelect.pair_id = payItem.pair_id;
      }
      const getItem = list.find(v => v.coin === val.get.coin);
      if (getItem) {
        this.coinSelect.get = getItem;
        this.coinSelect.get.number = null;
        this.coinSelect.pair_id = getItem.pair_id;
      }
      // 如果选择到一样的币种
      if (this.coinSelect.pay === this.coinSelect.get) {
        this.coinSelect.get = list.filter(v => v.coin !== val.pay.coin)[0]
        this.coinSelect.get.number = null;
      }

      this.handleBlanceIvit();
      this.handleGetPrice();
      this.handlePayYuguPrice(0);
    },
    // 监听账户等级变化
    user: {
      handler: function listen(val) {
        this.userInfo = val;
        if (this.userInfo && this.userInfo.remainFreeOrderCount === 0) {
          this.freeCpuChecked = false;
        }
      },
      deep: true,
    },
  },
  computed: {},
  created() {
    if (this.embed) {
      this.coinSelect.pay.coin = 'USN';
      this.coinSelect.get.coin = 'EOS';
    }
  },
  mounted() {
    this.userInfo = this.user;
  },
  beforeDestroy() {
    window.removeEventListener('message', this.handleReceiveMessage, false);
  },
  methods: {
    // 兑换
    async handleSubmit() {
      const pay = this.coinSelect.pay;
      const get = this.coinSelect.get;
      const payPriceForEos = this.handlePayPoolRate(1, pay.coin, true);
      // 余额不足
      if (parseFloat(this.balance) < Number(pay.number)) {
        this.$message.error(this.$t('jy.error3'));
        return;
      }
      if ((pay.coin === 'EOS' && Number(pay.number) < 0.1)
      || (get.coin === 'EOS' && Number(get.number) < 0.1)
      || (pay.coin !== 'EOS' && get.coin !== 'EOS' && (Number(pay.number) * Number(payPriceForEos)) < 0.1)) {
        this.errorCodexPay = true;
        this.loading = false;
        return;
      }
      // 没有做市商池子
      if (parseFloat(this.coinInfo.ygPrice) === 0) {
        this.$message.error(this.$t('swap.s94'));
        return;
      }
      if (this.loading) return;
      this.loading = true;
      const status = await this.handleServerStatus({});
      // 优先判断服务状态
      if (status === 0) {
        this.stopSwapType = 0;
        this.stopSwap = true;
        this.loading = false;
        return;
      }
      let symbolStatus = 1;
      if (status === 1) {
        const obj = { symbolStatus: 1 }
        symbolStatus = await this.handleServerStatus(obj);
      }
      // 优先判断服务状态
      if (symbolStatus === 0) {
        this.stopSwapType = 1;
        this.stopSwap = true;
        this.loading = false;
        return;
      }
      // const pool = this.handleReturnPool();
      // let pairIds = pool.pair_id;
      // if (pool.pools) {
      //   pairIds = `${pool.pools.payPool.pair_id}-${pool.pools.getPool.pair_id}`;
      // }
      const params = {
        contract: pay.contract,
        quantity: `${toFixed(Number(pay.number), pay.decimal)} ${pay.coin}`,
        memo: `swap-${get.contract}-${get.coin}`,
        freeCpu: this.freeCpuChecked
      }
      const accountItem = this.$store.state.app.scatter.identity.accounts[0];
      const formName = accountItem.name;
      if (this.scatter.by === 'mobileWallet') {
        // this.$emit('listenCodex', 'walletByPhone');
        this.payData = {
          type: 3, // 1买入， 2卖出, 3兑换
          coin: get.coin,
          jijiaCoin: pay.coin, // 计价币种
          price: toFixed(Number(this.coinInfo.ygPrice), pay.decimal), // 价格
          number: get.number, // 数量
          money: pay.number, // 交易额
          action: {
            fromAccount: formName,
            toAccount: 'swap.newdex',
            amount: params.quantity,
            memo: params.memo,
            contract: pay.contract,
            symbol: pay.coin,
            precision: pay.decimal // 精度
          },
        }
        this.tradingPay = true;
        this.loading = false;
        return;
      }
      if (this.embed) { // 如果是内嵌
        window.removeEventListener('message', this.handleReceiveMessage, false);
        window.addEventListener('message', this.handleReceiveMessage, false);
        const targetOrigin = getTargetOrigin();
        const permission = accountItem.authority;
        const dataItem = {
          actions: [
            {
              account: params.contract,
              name: 'transfer',
              authorization: [{
                actor: formName, // 转账者
                permission,
              }],
              data: {
                from: formName,
                to: 'swap.newdex',
                quantity: params.quantity,
                memo: params.memo
              }
            }
          ]
        };
        const postParams = {
          action: 'eosTransaction',
          data: dataItem,
          useFreeCpu: params.freeCpu
        }
        // console.log(postParams)
        // console.log(targetOrigin)
        window.parent.postMessage(JSON.stringify(postParams), targetOrigin);
        return;
      }
      bitModel.codexTransfer(params, (res) => {
        this.loading = false;
        if (res && (res.broadcast || res.processed)) {
          this.$emit('listenCodex', 'getSysbolInfo');
          if (this.freeCpuChecked) {
            this.$emit('listenCodex', 'getAccountInfo');
          }
          // 下单成功刷新订单列表
          setTimeout(() => {
            this.handleChange();
          }, 2000);
          this.handleBlanceIvit();
          this.$message.success(this.$t('newpos.successfulOperation'));
          return
        }
        bitModel.handleScatterErrorBack(res)
      })
    },

    // 嵌入交易代码 addEventListener message callback
    handleReceiveMessage(event) {
      // 这里不准确，chrome没有这个属性
      const origin = event.origin || event.originalEvent.origin;
      if (origin === window.location.origin) return;
      const message = JSON.parse(event.data);
      switch (message.action) {
        case 'eosTransaction': {
          const res = message.data.res;
          this.loading = false;
          if (res && (res.broadcast || res.processed)) {
            this.$emit('listenCodex', 'getSysbolInfo');
            if (this.freeCpuChecked) {
              this.$emit('listenCodex', 'getAccountInfo');
            }
            // 下单成功刷新订单列表
            setTimeout(() => {
              this.handleChange();
            }, 2000);
            this.handleBlanceIvit();
            this.$message.success(this.$t('newpos.successfulOperation'));
          }
          break;
        }
        default:
      }
    },

    // 获取当前价格
    handleGetPrice() {
      if (this.coinSelect.pay.coin === 'EOS') {
        // const symbol = `${this.coinSelect.get.coin}/${this.coinSelect.pay.coin}`;
        // const item = this.symbolList.find(v => v.symbol === symbol);
        // if (item) {
        //   this.coinInfo.price = item.bqPrice;
        // }
        const symbol = `${this.coinSelect.get.coin}/${this.coinSelect.pay.coin}`;
        const item = this.symbolList.find(v => v.symbol === symbol);
        if (item) {
          this.coinInfo.price = item.qbPrice;
          this.coinInfo.bl = item.bqPrice;
        }
      }
      if (this.coinSelect.get.coin === 'EOS') {
        const symbol = `${this.coinSelect.pay.coin}/${this.coinSelect.get.coin}`;
        const item = this.symbolList.find(v => v.symbol === symbol);
        if (item) {
          this.coinInfo.price = item.qbPrice;
          this.coinInfo.bl = item.qbPrice;
        }
      }
      if (this.coinSelect.pay.coin !== 'EOS' && this.coinSelect.get.coin !== 'EOS') {
        let payPrice = 0;
        let getPrice = 0;
        const paySymbol = `${this.coinSelect.pay.coin}/EOS`;
        const payItem = this.symbolList.find(v => v.symbol === paySymbol);
        if (payItem) {
          payPrice = Number(payItem.bqPrice);
        }
        const getSymbol = `${this.coinSelect.get.coin}/EOS`;
        const getItem = this.symbolList.find(v => v.symbol === getSymbol);
        if (getItem) {
          getPrice = Number(getItem.bqPrice);
        }
        this.coinInfo.price = toFixed(accDiv(getPrice, payPrice), 8);
        this.coinInfo.bl = this.coinInfo.price;
      }
    },

    /*
    * 获取预估成交价
    * @num 支付币种数量
    * */
    handlePayYuguPrice(number) {
      if (this.coinSelect.pay.coin === 'EOS' || this.coinSelect.get.coin === 'EOS') {
        this.coinInfo.ygPrice = this.handlePayPoolRate(number, this.coinSelect.get.coin, true);
        if (this.coinSelect.get.coin === 'EOS') {
          this.coinInfo.ygPrice = this.handlePayPoolRate(number, this.coinSelect.pay.coin, true);
        }
        this.coinInfo.ygPrice = toFixed(this.coinInfo.ygPrice, 8);
      }
      if (this.coinSelect.pay.coin !== 'EOS' && this.coinSelect.get.coin !== 'EOS') {
        const payLv = this.handlePayPoolRate(number, this.coinSelect.pay.coin, true);
        const getLv = this.handlePayPoolRate(number, this.coinSelect.get.coin, false, payLv);
        this.coinInfo.ygPrice = toFixed(Number(getLv), 8);
      }
      let p = accSub(Number(this.coinInfo.price), Number(this.coinInfo.ygPrice));
      if (this.coinSelect.pay.coin === 'EOS' && this.coinSelect.get.coin !== 'EOS') {
        const pp = accDiv(1, this.coinInfo.ygPrice);
        p = accSub(Number(this.coinInfo.price), pp);
      }
      const yjlv = accDiv(p, Number(this.coinInfo.price)); // 溢价率 =（当前价格-预估成交价）/ 当前价格
      this.coinInfo.yjlv = toFixed(toNonExponential(yjlv * 100), 2);
    },

    /*
    * 获取反算预估成交价
    * @num 支付币种数量
    * */
    handleGetYuguPrice(number) {
      if (this.coinSelect.pay.coin === 'EOS') {
        return this.handleGetPoolRate(number, this.coinSelect.get.coin, true);
      }
      if (this.coinSelect.get.coin === 'EOS') {
        return this.handleGetPoolRate(number, this.coinSelect.pay.coin, true);
      }
      if (this.coinSelect.pay.coin !== 'EOS' && this.coinSelect.get.coin !== 'EOS') {
        const getNum = this.handleGetPoolRate(number, this.coinSelect.get.coin, true);
        const getPayNumbr = this.handleGetPoolRate(number, this.coinSelect.pay.coin, false, getNum);
        return getPayNumbr;
      }
      return 0
    },

    /**
     * 兑换率 pool(NDX/EOS)
     * @param number // 支付数量
     * @param coin // 币种
     * @param isBase // 是否为基础币之间兑换
     * @param payNum // 支付滑点价格
    */
    handlePayPoolRate(number, coin, isBase, payNum) {
      // 例子 1ETH(计价币) 兑换 BAT(基础币)
      // 计算收到的 BAT 公式如下
      // 计价币池总量 + （num - (手续费 * num)）= a
      // 不变量 / a = b
      // BAT = 基础币池总量 - b
      const num = Number(number) || 1;
      const symbol = `${coin}/EOS`;
      const item = this.symbolList.find(v => v.symbol === symbol);
      if (item) {
        const quoteQuantity = parseFloat(item.quote_quantity);
        const baseQuantity = parseFloat(item.base_quantity);
        // 开始计算 accAdd + 、accSub -、accMul *、accDiv /
        let a = accAdd(quoteQuantity, accSub(num, accMul(num, this.shouxufei)));
        let b = accDiv(item.invariant, a);
        // 兑换率、预估价格
        let bob = accSub(baseQuantity, b);
        if (this.coinSelect.get.coin === 'EOS') {
          a = accAdd(baseQuantity, accSub(num, accMul(num, this.shouxufei)));
          b = accDiv(item.invariant, a);
          // 兑换率、预估价格
          bob = accSub(quoteQuantity, b);
        }
        if (this.coinSelect.pay.coin !== 'EOS' && this.coinSelect.get.coin !== 'EOS') {
          a = accAdd(baseQuantity, accSub(num, accMul(num, this.shouxufei)));
          b = accDiv(item.invariant, a);
          bob = accSub(quoteQuantity, b);
          if (!isBase) {
            a = accAdd(quoteQuantity, accSub(payNum, accMul(payNum, this.shouxufei)));
            b = accDiv(item.invariant, a);
            // 兑换率、预估价格
            bob = accSub(baseQuantity, b);
            return accDiv(bob, num);
          }
          return bob;
        }
        // console.log(baseQuantity, a * 1);
        return accDiv(bob, num);
      }
      return 0;
    },


    /**
     * 兑换率 pool(NDX/EOS)
     * @param number // 得到支付数量
     * @param coin // 币种
     * @param isBase // 是否为基础币之间兑换
     * @param payNum // 支付滑点价格
    */
    handleGetPoolRate(number, coin, isBase, getNum) {
      // 例子 1ETH(计价币) 兑换 BAT(基础币)
      // 计算收到的 BAT 公式如下
      // 计价币池总量 + （num - (手续费 * num)）= a
      // 不变量 / a = b
      // BAT = 基础币池总量 - b
      const num = Number(number) || 1;
      const symbol = `${coin}/EOS`;
      const item = this.symbolList.find(v => v.symbol === symbol);
      if (item) {
        const quoteQuantity = parseFloat(item.quote_quantity);
        const baseQuantity = parseFloat(item.base_quantity);
        // 开始计算 accAdd + 、accSub -、accMul *、accDiv /
        let b = baseQuantity - num;
        let a = item.invariant / b;
        let c = a - quoteQuantity;
        let pn = c / (1 - this.shouxufei);

        if (this.coinSelect.get.coin === 'EOS') {
          b = quoteQuantity - num;
          a = item.invariant / b;
          c = a - baseQuantity;
          pn = c / (1 - this.shouxufei);
        }
        if (this.coinSelect.pay.coin !== 'EOS' && this.coinSelect.get.coin !== 'EOS') {
          b = baseQuantity - num;
          a = item.invariant / b;
          c = a - quoteQuantity;
          pn = c / (1 - this.shouxufei);
          if (!isBase) {
            b = quoteQuantity - getNum;
            a = item.invariant / b;
            c = a - baseQuantity;
            pn = c / (1 - this.shouxufei);
          }
        }
        return pn;
      }
      return 0;
    },

    // 支付额度输入
    handlePayNumberInput() {
      this.errorCodexPay = false;
      const pay = this.coinSelect.pay.number;
      this.handlePayYuguPrice(pay);
      this.coinSelect.get.number = toFixed(accMul(pay, Number(this.coinInfo.ygPrice)), this.coinSelect.get.decimal);
      this.$forceUpdate(); // 强制更新
    },
    // 得到额度输入
    handleGetNumberInput() {
      this.errorCodexPay = false;
      const get = Number(this.coinSelect.get.number);
      let pay = 0;
      if (get) {
        pay = toFixed(this.handleGetYuguPrice(get), this.coinSelect.pay.decimal);
      }
      this.coinSelect.pay.number = pay;
      this.coinInfo.ygPrice = toFixed(accDiv(Number(get), pay), 8);
      // const p = accSub(Number(this.coinInfo.bl), Number(this.coinInfo.ygPrice));
      // const yjlv = accDiv(p, Number(this.coinInfo.bl)); // 溢价率 =（当前价格-预估成交价）/ 当前价格
      // this.coinInfo.yjlv = toFixed(Number(yjlv) * 100, 2);
      this.handlePayYuguPrice(pay);
      this.$forceUpdate(); // 强制更新
    },

    // 跟换支付/得到 方向
    handleChangeCoin() {
      const payCoin = this.coinSelect.pay.coin;
      this.coinSelect.pay.coin = this.coinSelect.get.coin;
      this.coinSelect.get.coin = payCoin;
      this.coinSelect.timer = new Date().getTime();
    },

    // 余额获取
    handleBlanceIvit() {
      const scatter = this.scatter;
      if (scatter && scatter.identity && scatter.chain === 'eos') {
        let coin = this.coinSelect.pay.coin;
        if (coin === 'EOS') {
          coin = this.symbolScience;
        }
        bitModel.EosModel.getCurrencyBalance(coin, this.coinSelect.pay.contract, (result) => {
          if (result.error) return;
          let res = result;
          if (!res) return;
          if (res.length === 0) {
            res = 0;
          } else {
            res = result[0];
          }
          this.balance = toFixed(parseFloat(res, 0) || 0, this.coinSelect.pay.decimal);
        });
        return;
      }
      this.balance = toFixed(0, this.coinSelect.pay.decimal);
    },
    // 格式化数字精度
    handleNumberBlur(way, number, decimal) {
      this.coinSelect[way].number = toFixed(number, decimal);
      this.$forceUpdate();
    },

    // 登录授权
    handleWalletPermission(bychain) {
      const checkWallet = localStorage.getItem('checkWallet');
      sessionStorage.setItem('checkWalletByChain', bychain.toUpperCase());
      if (!Number(checkWallet)) {
        this.$emit('listenWalletPermission', true);
        return;
      }
      this.$emit('listenWalletLogin', true);
    },
    // 下单成功刷新订单
    handleChange() {
      const dataMarket = {
        activeType: 1,
        coinCode: '', // 模糊查询
        pairId: '', // 交易对ID
        fromCoin: '',
        toCoin: '',
        queryMonths: '', // 查询时间：1-近一个月；3-近三个月
      }
      Bus.$emit('handleChange', dataMarket);
    },
    // 服务状态
    handleServerStatus(obj) {
      this.payCodeStr = '';
      this.getCodeStr = '';
      return new Promise((resolve, reject) => {
        bitModel.swapServerStartus(obj, (res) => {
          if (res && res.rows && res.rows.length > 0) {
            let status = 1;
            if (obj.symbolStatus) {
              const rows = res.rows;
              if (this.coinSelect.pay.pair_id && this.coinSelect.pay.coin !== 'EOS') {
                const item = rows.find(v => v.pair_id === this.coinSelect.pay.pair_id);
                if (item) {
                  status = item.status;
                  this.payCodeStr = !status ? this.coinSelect.pay.coin : '';
                }
              }
              if (this.coinSelect.get.pair_id && this.coinSelect.get.coin !== 'EOS') {
                const item = rows.find(v => v.pair_id === this.coinSelect.get.pair_id);
                this.getCodeStr = this.coinSelect.get.coin;
                this.payCodeStr = '';
                if (item) {
                  status = item.status;
                  this.getCodeStr = !status ? this.coinSelect.get.coin : '';
                }
              }
              if (this.coinSelect.pay.coin !== 'EOS' && this.coinSelect.get.coin !== 'EOS') {
                const payStatus = rows.find(v => v.pair_id === this.coinSelect.pay.pair_id).status;
                const getStatus = rows.find(v => v.pair_id === this.coinSelect.get.pair_id).status;
                status = getStatus * payStatus;
                this.payCodeStr = !payStatus ? this.coinSelect.pay.coin : '';
                this.getCodeStr = !getStatus ? this.coinSelect.get.coin : '';
              }
            } else {
              status = Number(res.rows[0].value);
            }
            resolve(status); // 服务暂停
            return;
          }
          this.loading = false;
          reject('gggg');
          this.$message.error(this.$t('swap.s63'));
        })
      })
    },
    // 立即做市
    handleToMarket() {
      this.$emit('listenCodex', 'toMarket', this.handleReturnPool());
    },
    // 拿到当前池子
    handleReturnPool() {
      const pool = {
        symbol: 'NDX/EOS',
      }
      if (this.coinSelect.pay.coin === 'EOS') {
        pool.symbol = `${this.coinSelect.get.coin}/${this.coinSelect.pay.coin}`;
      }
      if (this.coinSelect.get.coin === 'EOS') {
        pool.symbol = `${this.coinSelect.pay.coin}/${this.coinSelect.get.coin}`;
      }
      if (this.coinSelect.get.coin !== 'EOS' && this.coinSelect.pay.coin !== 'EOS') {
        const payPool = this.symbolList.find(v => v.symbol === `${this.coinSelect.pay.coin}/EOS`);
        const getPool = this.symbolList.find(v => v.symbol === `${this.coinSelect.get.coin}/EOS`);
        pool.pools = { payPool, getPool };
        return pool;
      }
      const item = this.symbolList.find(v => v.symbol === pool.symbol);
      if (item) {
        return item;
      }
      return pool;
    },
    handleTips() {
      this.stopSwapType = 0;
      this.stopSwap = false;
    },
    accDiv(a, b) {
      if (Number(b) === 0) return 0;
      return accDiv(a, b);
    },
    toFixed(a, b) {
      return toFixed(a, b);
    },
  },
}
</script>
<style lang="scss" scoped>
@import "@/assets/css/variables.scss";

.exchange {
  background: #fff;
  margin-bottom: 20px;

  .main {
    padding: 30px 60px 30px;

    .cont {
      position: relative;
      min-height: 100px;
      align-items: end;

      & > div {
        flex: 1;
        width: 50%;

        &:nth-child(1) {
          padding-right: 50px;
        }

        &:nth-child(2) {
          padding-left: 50px;
        }

        .balance {
          font-size: 12px;
          color: #999;
        }
      }

      .centIcon {
        position: absolute;
        top: 56%;
        left: 50%;
        transform: translate(-50%, -80%);
        cursor: pointer;
        color: #4A90E2;
        padding: 4px;
        border-radius: 50%;
        border: 1px solid #4A90E2;
      }
    }

    .flexLeft {
      width: 90px;
      padding-bottom: 3px;
    }

    .flexRight {
      position: relative;
      width: 450px;
      margin-top: 35px;
      .errorCodexPay {
        position: absolute;
        left: 0;
        top: 40px;
      }
    }

    .nowPrice {
      margin-top: 40px;
      padding: 15px 10px 15px 25px;
      background: #F4F9FC;

      .nowPriceItem {
        flex: 0.6;
        margin-right: 50px;

        // span:nth-child(1) {
        //   color: #999;
        // }

        &:nth-child(2) {
          flex: 0.8;
        }
        &:nth-child(3) {
          flex: 1.2;
        }

        & > div:nth-child(1) {
          margin-bottom: 10px;
        }

        & > div:nth-child(2) {
          color: #999;
        }
      }
    }

    .btn {
      width: 350px;
      margin-top: 10px;
    }
  }

  /deep/ .el-select .el-input, /deep/ .el-input-group__prepend {
    width: 130px;
  }

  /deep/ .el-input-group__prepend .slotCls span {
      width: 53px;
      overflow: hidden;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      max-width: 53px;
      display: inline-block;
    }

  // /deep/ .el-input-group__prepend {
  //   background: #fff;
  // }

  .selectClass {
    position: relative;
    width: 100%;
    /deep/ .el-input__inner {
      padding-left: 40px;
    }
    .slotClass {
      width: 140px;
      line-height: 38px;
      height: 38px;
      position: absolute;
      top: 1px;
      left: 0;
      color: #333;
      padding-left: 5px;

      .checkAreaImg {
        position: relative;
        display: block;
        width: 25px;
        height: 25px;

        &::before {
          position: absolute;
          top: 0;
          left: 0;
          content: '';
          display: block;
          width: 25px;
          height: 25px;
          background: url('https://ndi.340wan.com/eos/eosio.token-eos.png') no-repeat;
          background-size: 100% 100%;
        }
      }
    }
  }

  /deep/ .el-message {
    top: 250px !important;
    min-width: auto;
  }
  /deep/ .el-select-dropdown__item {
    padding-left: 5px;
  }
  .tipCls {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
    height: 17px;
  }
}

.theme-1B1D27 {
  .balance {
    color: $-opacity8 !important;
  }

  .main {
    background: $-black2 !important;
  }

  /deep/ .input-with-select .el-input-group__prepend {
    background: $-black1 !important;
  }

  .nowPrice {
    background: $-black1 !important;
  }

  .nowPriceItem {
    span:nth-child(1) {
      color: $-opacity8 !important;
    }
  }
}

// dialog 样式
.dialogPay{
  /deep/ .el-dialog{
    background: url('../../../assets/img/wallet/bg-financial.png') no-repeat;
    color: white;
    position: relative;

    .el-icon-close{
      color: white;
    }

    .dialog-logo{
      position: absolute;
      font-size: 30px;
      left: 30px;
      top: 20px;
    }
  }

  /deep/ .el-dialog__body{
    padding: 0px;
  }
}
</style>
